package org.ns.learn.rpc.codec;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.nio.charset.Charset;
import java.util.List;

public class RpcMessageResponseDecode extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes()  <  4) {
            return;
        }

        in.markReaderIndex();
        int length = in.readInt();

        if (in.readableBytes() < length) {
            in.resetReaderIndex();
            return;
        }

        byte[] body = new byte[length];
        in.readBytes(body);
        String json = new String(body, Charset.forName("UTF-8"));
//        System.out.println("rpc应答:" + json);
        RpcResponse response = JSON.parseObject(json, RpcResponse.class);
        response.setResult(DecodeUtils.toObject(response.getResult(), response.getParameterType()));
        out.add(response);
    }
}
